<template>
  <nut-popup
    :visible="show"
    position="bottom"
    :safe-area-inset-bottom="safeAreaInsetBottom"
    @open="handleOpen"
    @close="handleClose"
  >
    <view class="dpr-center-center pt-3 px-3">
      <input
        v-model="content"
        class="input-text"
        :focus="focus"
        :cursor="value.length"
        :adjust-position="false"
        :maxlength="maxLength"
        :placeholder="placeholder"
        :style="{ backgroundColor: '#fafafa' }"
        @keyboardheightchange="getHeight"
        @focus="getHeight"
        @change="handleContentChange"
        @blur="leaveInput"
        @confirm="handleCommit"
      />
      <view :style="{ color: content || !required ? '#fa0435' : '#909090' }" class="confirm-text" @click="handleCommit"
        >{{ btnText }}
      </view>
    </view>
    <view v-if="show" :style="{ height: `${keyBoardHeight}px` }" />
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import './index.less';
import Taro from '@tarojs/taro';
import { isImmutable } from 'immutable';

const windowInfo = Taro.getWindowInfo();
const props = defineProps({
  btnText: {
    type: String,
    default: '确认',
  },
  value: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '',
  },
  autoHeight: {
    type: Boolean,
    default: false,
  },
  required: {
    type: Boolean,
    default: false,
  },
  inputHeight: {
    type: [Number, String],
    default: 1,
  },
  rows: {
    type: [Number, String],
    default: 1,
  },
  maxLength: {
    type: [Number, String],
    default: 12,
  },
  show: {
    type: Boolean,
    default: false,
  },
});
const content = ref(props.value);
const focus = ref(false);
const keyBoardHeight = ref(0);
const safeAreaInsetBottom = ref(true);
const handleContentChange = (val) => {
  console.log();
};
const leaveInput = (e) => {
  keyBoardHeight.value = 0;
  safeAreaInsetBottom.value = true; // 输入框失去焦点时让距离底部距离为 0
};

const getHeight = (e) => {
  console.log(e, 'INPUT获取输入法高度');
  keyBoardHeight.value = e.target.height + 10; // 获取输入法的高度，动态设置输入框距离顶部距离。
  if (e.target.height > 0) {
    safeAreaInsetBottom.value = false;
  }
};

const emit = defineEmits(['close', 'open', 'commit']);
const handleCommit = () => {
  if (props.required && !content.value) {
    return;
  }
  emit('commit', content.value);
};
const handleClose = () => {
  emit('close', props.show);
};
const handleOpen = () => {
  emit('open', props.show);
};
watch(
  () => props.show,
  (n, o) => {
    setTimeout(() => {
      console.log('监听显示');
      focus.value = n;
    }, 1);
  },
  { immediate: true },
);
</script>

<style lang="less" scoped></style>
